package org.piggy.core.filter.auth;

import io.netty.handler.codec.http.cookie.Cookie;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.piggy.common.constants.FilterConst;
import org.piggy.common.enums.ResponseCode;
import org.piggy.common.exception.ResponseException;
import org.piggy.core.context.GatewayContext;
import org.piggy.core.filter.Filter;
import org.piggy.core.filter.FilterAspect;
import org.piggy.core.utils.JwtUtil;

@Slf4j
@FilterAspect(id= FilterConst.AUTH_FILTER_ID, name = FilterConst.AUTH_FILTER_NAME, order = FilterConst.AUTH_FILTER_ORDER )
public class AuthFilter implements Filter {

    private static final String COOKIE_NAME = "cookie-jwt";

    @Override
    public void doFilter(GatewayContext gatewayContext) {
        try {
            if (gatewayContext.getRule().getFilterConfig(FilterConst.AUTH_FILTER_ID) == null) {
                return;
            }
            Cookie cookie = gatewayContext.getGatewayRequest().getCookie(COOKIE_NAME);
            if(cookie != null){
                String token = cookie.value();
                if (StringUtils.isNotEmpty(token)) {
                    String userId = JwtUtil.decode(token);
                    gatewayContext.getGatewayRequest().setUserId(userId);
                    return;
                }
            }
            throw new ResponseException(ResponseCode.UNAUTHORIZED);
        } catch (Exception e) {
            throw new ResponseException(ResponseCode.UNAUTHORIZED);
        }
    }

}
